package com.seabook.happy.website.servlets;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Category;
import com.seabook.happy.website.daos.MoodDao;
import com.seabook.happy.website.pojos.Mood;

public class MoodUpdateServlet extends HttpServlet {
	private MoodDao moodDao = new MoodDao();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String requestActionParam = req.getParameter("action");
		if ("new".equals(requestActionParam)) {
			createMood(req, resp);
		} else if ("update".equals(requestActionParam)) {
			//TODO
		} else if ("del".equals(requestActionParam)) {
			deleteMood(req, resp);
		} else {
			//TODO
		}
	}
	
	private void createMood(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String moodMsg = (String) req.getParameter("mood-content");
		String moods = (String) req.getParameter("moods-option");
		Date date = new Date();
		Mood mood = new Mood(moodMsg, date, new Category(decideMood(moods)));
		moodDao.insertMood(mood);
		resp.sendRedirect("homepage.jsp");
	}

	private String decideMood(String moods) {
		String returnStr = Mood.HAPPY;
		if (moods.equalsIgnoreCase(Mood.HAPPY)) {
			returnStr = Mood.HAPPY;
		} else if (moods.equalsIgnoreCase(Mood.UNHAPPY)) {
			returnStr = Mood.UNHAPPY;
		} else
			returnStr = Mood.SOSO;
		return returnStr;
	}

	private boolean deleteMood(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = (String) req.getParameter("mood-id");
		moodDao.deleteMood(id);
		resp.sendRedirect("listAllMoods.jsp");
		return true;
	}
}
